<?php 

include 'config.php';
 require 'dbcon.php';
//登录数据库服务器
//session_start();
$conn=mysql_connect($config['host'],$config['user'],$config['password']);
//选择数据库
mysql_select_db($config['database'],$conn);
//设置编码集
mysql_set_charset($config['charset']);
//执行sql语句
//a)插入

function  insert($table,$data){
    //insert into 表名（字段1，字段2，....） values(值1，值2....)；
     $keys=array_keys($data);
    $fields= implode(',', $keys);
    $values= array_values($data);
    $vals=implode('","', $values);
    $sql='insert into ' .$table.' ('.$fields.')'.'values("'.$vals.'") ';
    $res= mysql_query($sql);
    if($res){
    return array(
        'status'=>1,
        'msg'=>'插入成功!'
    );
    }
    else
    {
        return array(
          'status'=>0,
           'msg'=>'插入失败'
       );
    }
}
//b)删除
function  delete(){
    
}
//c)修改

function update($table,$data,$id){
    $str='';
    foreach ($data as $key=>$val){
        $str .=$key . '=" ' . $val . '",';
    }
    $str = substr($str, 0, -1);
    $sql='update ' . $table . ' set ' . $str . ' where id=' . $id;
    header('content-type:text/html;charset=utf-8 ');
    
    $res= mysql_query($sql);
    if($res){
    return array(
        'status'=>1,
        'msg'=>'添加成功!'
    );
    }
}
//d)查找
function find($table,$opt=false){
    if ($opt) {
    $keys=array_keys($opt);
    $vals= array_values($opt);
    $sql='select * from ' . $table .' where  ' . $keys[0] . '="' . $vals[0] . '"';
    } else {
        $sql='select * from  ' . $table;
    }
    
    $res= mysql_query($sql);
    $rows= array();
    while ($row= mysql_fetch_assoc($res)){
        $rows[]=$row;
    }
    return $rows;
}
//用来检查登录
function checklogin()
{
    if(!$_SESSION['loginfo']){
     header('Location:login.php');
     exit();
 }
}


//分页查找
function findByPage($page=1,$size=5){
    $offset=($page-1)*$size;
    //$sql='select * from ' . $table .' limit ' . $offset . ' , ' . $size;
    $sql = 'select p.id,p.title,u.nickname,p.content,p.views,p.likes,p.feature, c.name,p.created,p.`status`  from `posts`  
    as p left join users as u on p.user_id=u.id left join 
    categories as c on p.category_id=c.id limit ' . $offset . ' , ' . $size;
      
    $res=mysql_query($sql);
    while ($row = mysql_fetch_assoc($res)){
        $rows[]=$row;
    }
    return $rows;
}